package co.edu.unal.franquicias.mastercard.activities;

import co.edu.unal.franquicias.mastercard.domain.DebitCardTransaction;
import co.edu.unal.franquicias.mastercard.domain.ValidationStatus;
import co.edu.unal.franquicias.mastercard.exceptions.CannotValidateTransactionException;
import co.edu.unal.franquicias.mastercard.repositories.ValidateVisa;
import co.edu.unal.franquicias.mastercard.representations.DebitCardTransactionRepresentation;
import co.edu.unal.franquicias.mastercard.representations.VisaUri;
import co.edu.unal.franquicias.mastercard.util.Constants;
import co.edu.unal.franquicias.mastercard.util.ServiceLocator;

public class ValidateDebitCardTransactionActivity {

	public DebitCardTransactionRepresentation validate(
			DebitCardTransaction transaction, VisaUri visaUri)
			throws CannotValidateTransactionException {

		// perform validation
		transaction.setValidationStatus(doValidation(transaction));

		return DebitCardTransactionRepresentation
				.createResponseTransactionRepresentation(transaction, visaUri);
	}

	private ValidationStatus doValidation(
			DebitCardTransaction debitCardTransaction)
			throws CannotValidateTransactionException {
		try {

			ValidateVisa validateVisa = (ValidateVisa) ServiceLocator
					.getInstance().getResource(Constants.VISA_EJB);

			if (validateVisa.validateDeditCardTransaction(debitCardTransaction)) {
				return ValidationStatus.VALID;
			}

			return ValidationStatus.INVALID;

		} catch (Exception e) {
			throw new CannotValidateTransactionException(e);
		}
	}
}
